<template>
  <common-layout title="EBOM管理">
    <template #header-buttons>
      <div class="card-header">
        <el-button type="primary" @click="handleCreate">新增BOM</el-button>
      </div>
    </template>

    <template #search-form>
      <el-form :model="searchForm" inline>
        <el-form-item label="BOM编码">
          <el-input v-model="searchForm.bomCode" placeholder="请输入BOM编码"></el-input>
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input v-model="searchForm.materialName" placeholder="请输入物料名称"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="全部" value=""></el-option>
            <el-option label="未审核" value="0"></el-option>
            <el-option label="已审核" value="1"></el-option>
            <el-option label="已启用" value="2"></el-option>
            <el-option label="已禁用" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </template>

    <template #data-content>
      <!-- BOM列表 -->
      <el-table v-loading="loading" :data="ebomList" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="bomCode" label="BOM编码" width="180"></el-table-column>
        <el-table-column prop="materialId" label="物料ID" width="120"></el-table-column>
        <el-table-column prop="materialName" label="物料名称" width="180"></el-table-column>
        <el-table-column prop="version" label="版本" width="100"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0" type="warning">未审核</el-tag>
            <el-tag v-if="scope.row.status === 1" type="info">已审核</el-tag>
            <el-tag v-if="scope.row.status === 2" type="success">已启用</el-tag>
            <el-tag v-if="scope.row.status === 3" type="danger">已禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdBy" label="创建人" width="120"></el-table-column>
        <el-table-column prop="createdTime" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="success" @click="handleApprove(scope.row)" v-if="scope.row.status === 0">审核</el-button>
            <el-button size="small" type="warning" @click="handleEnable(scope.row)" v-if="scope.row.status === 1">启用</el-button>
            <el-button size="small" type="danger" @click="handleDisable(scope.row)" v-if="scope.row.status === 2">禁用</el-button>
            <el-button size="small" type="info" @click="handleNewVersion(scope.row)">新版本</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
      </div>
    </template>
  </common-layout>

  <!-- 查看BOM对话框 -->
  <el-dialog v-model="viewDialogVisible" title="查看BOM" width="800px">
    <el-form :model="currentEBOM" label-width="100px" size="small">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="BOM编码">
            <el-input v-model="currentEBOM.bomCode" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="版本">
            <el-input v-model="currentEBOM.version" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物料ID">
            <el-input v-model="currentEBOM.materialId" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物料名称">
            <el-input v-model="currentEBOM.materialName" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="BOM结构明细">
            <el-tree
              :data="currentEBOM.ebomItems || []"
              :props="treeProps"
              node-key="id"
              default-expand-all
              style="width: 100%;"
            >
              <template #default="{ node, data }">
                <div class="tree-node-content">
                  <span>{{ data.materialName }} ({{ data.materialId }})</span>
                  <div class="tree-node-actions">
                    <span>数量: {{ data.quantity }}</span>
                    <span style="margin-left: 15px;">单位: {{ data.unit }}</span>
                    <span style="margin-left: 15px;">位置: {{ data.position }}</span>
                    <span style="margin-left: 15px;">备注: {{ data.remark }}</span>
                  </div>
                </div>
              </template>
            </el-tree>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="viewDialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>

  <!-- 创建/编辑BOM对话框 -->
  <el-dialog v-model="formDialogVisible" :title="isEdit ? '编辑BOM' : '创建BOM'" width="800px">
    <el-form ref="bomForm" :model="formData" :rules="formRules" label-width="100px" size="small">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="BOM编码" prop="bomCode" v-if="isEdit">
            <el-input v-model="formData.bomCode" disabled></el-input>
          </el-form-item>
          <el-form-item label="BOM编码" prop="bomCode" v-else>
            <el-input v-model="formData.bomCode" placeholder="请输入BOM编码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="版本" prop="version" v-if="isEdit">
            <el-input v-model="formData.version" disabled></el-input>
          </el-form-item>
          <el-form-item label="版本" prop="version" v-else>
            <el-input v-model="formData.version" placeholder="请输入版本"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物料ID" prop="materialId">
            <el-input v-model="formData.materialId" placeholder="请输入物料ID"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物料名称" prop="materialName">
            <el-input v-model="formData.materialName" placeholder="请输入物料名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="BOM结构明细">
            <el-tree
              :data="formData.ebomItems"
              :props="treeProps"
              node-key="id"
              default-expand-all
              style="width: 100%; margin-bottom: 20px;"
            >
              <template #default="{ node, data }">
                <div class="tree-node-content">
                  <span>{{ data.materialName }} ({{ data.materialId }})</span>
                  <div class="tree-node-actions">
                    <el-input
                      v-model="data.quantity"
                      type="number"
                      placeholder="数量"
                      size="small"
                      style="width: 80px; margin-right: 10px;"
                    ></el-input>
                    <el-input
                      v-model="data.unit"
                      placeholder="单位"
                      size="small"
                      style="width: 80px; margin-right: 10px;"
                    ></el-input>
                    <el-input
                      v-model="data.position"
                      placeholder="位置"
                      size="small"
                      style="width: 80px; margin-right: 10px;"
                    ></el-input>
                    <el-input
                      v-model="data.remark"
                      placeholder="备注"
                      size="small"
                      style="width: 150px; margin-right: 10px;"
                    ></el-input>
                    <el-button
                      size="small"
                      type="primary"
                      @click.stop="addChildBomItem(data)"
                    >
                      添加子项
                    </el-button>
                    <el-button
                      size="small"
                      type="danger"
                      @click.stop="removeBomItem(data.id)"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
              </template>
            </el-tree>
            <el-button type="primary" size="small" @click="addRootBomItem">添加根物料</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="formDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>

  <!-- 新建版本对话框 -->
  <el-dialog v-model="newVersionDialogVisible" title="新建版本" width="600px">
    <el-form ref="newVersionForm" :model="newVersionForm" :rules="newVersionRules" label-width="100px" size="small">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="当前版本">
            <el-input v-model="newVersionForm.currentVersion" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="新版本号" prop="newVersion">
            <el-input v-model="newVersionForm.newVersion" placeholder="请输入新版本号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="变更原因" prop="changeReason">
            <el-input v-model="newVersionForm.changeReason" type="textarea" placeholder="请输入变更原因"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="newVersionDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitNewVersion">确定</el-button>
    </template>
  </el-dialog>

  <!-- 删除确认对话框 -->
  <el-dialog v-model="deleteDialogVisible" title="确认删除" width="400px">
    <p>确定要删除BOM <strong>{{ currentEBOM.bomCode }}</strong> 吗？此操作不可撤销。</p>
    <template #footer>
      <el-button @click="deleteDialogVisible = false">取消</el-button>
      <el-button type="danger" @click="confirmDelete">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import CommonLayout from '@/components/CommonLayout.vue';
import { getEBOMs, getEBOMById, createEBOM, updateEBOM, approveEBOM, enableEBOM, disableEBOM, createNewVersion, deleteEBOM } from '@/api/ebom.js';

type EBOMStatus = 0 | 1 | 2 | 3;

type BOMItem = {
  id: number;
  materialId: string;
  materialName: string;
  quantity: number;
  unit: string;
  position: string;
  remark: string;
  children?: BOMItem[];
};

type EBOM = {
  id: number;
  bomCode: string;
  version: string;
  materialId: string;
  materialName: string;
  status: EBOMStatus;
  createdBy: string;
  createdTime: string;
  ebomItems: BOMItem[];
};

// 搜索表单
const searchForm = reactive<{ bomCode: string; materialName: string; status: string }>({
  bomCode: '',
  materialName: '',
  status: ''
});

// BOM列表数据
const ebomList = ref<EBOM[]>([]);
const loading = ref(false);

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 详情对话框
const viewDialogVisible = ref(false);
const currentEBOM = reactive<Partial<EBOM>>({});

// 创建/编辑对话框
const formDialogVisible = ref(false);
const isEdit = ref(false);
const formData = reactive<Partial<EBOM>>({
  id: 0,
  bomCode: '',
  version: '',
  materialId: '',
  materialName: '',
  ebomItems: []
});

// 表单规则
const formRules = {
  bomCode: [{ required: true, message: '请输入BOM编码', trigger: 'blur' }],
  version: [{ required: true, message: '请输入版本', trigger: 'blur' }],
  materialId: [{ required: true, message: '请输入物料ID', trigger: 'blur' }],
  materialName: [{ required: true, message: '请输入物料名称', trigger: 'blur' }]
};

// 新建版本对话框
const newVersionDialogVisible = ref(false);
const newVersionForm = reactive({
  currentVersion: '',
  newVersion: '',
  changeReason: '',
  bomId: 0
});

// 新建版本表单规则
const newVersionRules = {
  newVersion: [{ required: true, message: '请输入新版本号', trigger: 'blur' }],
  changeReason: [{ required: true, message: '请输入变更原因', trigger: 'blur' }]
};

// 删除确认对话框
const deleteDialogVisible = ref(false);

// 加载BOM列表
const loadEBOMList = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      bomCode: searchForm.bomCode,
      materialName: searchForm.materialName,
      status: searchForm.status
    };
    const response = await getEBOMs(params);
    ebomList.value = response?.$values || [];
    pagination.total = response?.totalCount || 0;
  } catch (error) {
    ElMessage.error('获取BOM列表失败: ' + (error as Error).message);
    console.error('Failed to load EBOM list:', error);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  loadEBOMList();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key as keyof typeof searchForm] = '';
  });
  pagination.currentPage = 1;
  loadEBOMList();
};

// 分页大小变更
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  loadEBOMList();
};

// 当前页码变更
const handleCurrentChange = (current: number) => {
  pagination.currentPage = current;
  loadEBOMList();
};

// 查看BOM详情
const handleView = async (ebom: EBOM) => {
  loading.value = true;
  try {
    const response = await getEBOMById(ebom.id);
    Object.assign(currentEBOM, response);
    viewDialogVisible.value = true;
  } catch (error) {
    ElMessage.error('获取BOM详情失败: ' + (error as Error).message);
    console.error('Failed to get EBOM detail:', error);
  } finally {
    loading.value = false;
  }
};

// 创建BOM
const handleCreate = () => {
  isEdit.value = false;
  // 重置表单数据
  Object.assign(formData, {
    id: 0,
    bomCode: '',
    version: '',
    materialId: '',
    materialName: '',
    ebomItems: []
  });
  formDialogVisible.value = true;
};

// 编辑BOM
const handleEdit = async (ebom: EBOM) => {
  isEdit.value = true;
  loading.value = true;
  try {
    const response = await getEBOMById(ebom.id);
    Object.assign(formData, response);
    formDialogVisible.value = true;
  } catch (error) {
    ElMessage.error('获取BOM详情失败: ' + (error as Error).message);
    console.error('Failed to get EBOM detail:', error);
  } finally {
    loading.value = false;
  }
};

// 树形结构配置
const treeProps = {
  children: 'children',
  label: 'materialName'
};

// 生成唯一ID
let nextId = 1;
const generateId = () => nextId++;

// 添加根物料项
const addRootBomItem = () => {
  if (!formData.ebomItems) {
    formData.ebomItems = [];
  }
  formData.ebomItems.push({
    id: generateId(),
    materialId: '',
    materialName: '',
    quantity: 1,
    unit: '',
    position: '',
    remark: '',
    children: []
  });
};

// 添加子物料项
const addChildBomItem = (parent: BOMItem) => {
  if (!parent.children) {
    parent.children = [];
  }
  parent.children.push({
    id: generateId(),
    materialId: '',
    materialName: '',
    quantity: 1,
    unit: '',
    position: '',
    remark: '',
    children: []
  });
};

// 递归查找并移除物料项
const removeBomItem = (id: number, items?: BOMItem[]) => {
  const targetItems = items || formData.ebomItems;
  if (!targetItems) return;

  for (let i = 0; i < targetItems.length; i++) {
    if (targetItems[i].id === id) {
      targetItems.splice(i, 1);
      return true;
    }
    if (targetItems[i].children && removeBomItem(id, targetItems[i].children)) {
      return true;
    }
  }
  return false;
};

// 提交表单
const bomForm = ref(null);
const handleSubmit = async () => {
  try {
    await (bomForm.value as any).validate();
    if (isEdit.value && formData.id) {
      // 编辑BOM
      await updateEBOM(formData.id, formData);
      ElMessage.success('编辑BOM成功');
    } else {
      // 创建BOM
      await createEBOM(formData);
      ElMessage.success('创建BOM成功');
    }
    formDialogVisible.value = false;
    loadEBOMList();
  } catch (error) {
    if ((error as any).name === 'ValidationError') {
      return;
    }
    ElMessage.error(isEdit.value ? '编辑BOM失败' : '创建BOM失败');
    console.error(isEdit.value ? 'Failed to update EBOM:' : 'Failed to create EBOM:', error);
  }
};

// 审核BOM
const handleApprove = async (ebom: EBOM) => {
  try {
    // 假设当前用户ID为1，实际应从登录信息中获取
    const approvedBy = 1;
    await approveEBOM(ebom.id, approvedBy);
    ElMessage.success('审核BOM成功');
    loadEBOMList();
  } catch (error) {
    ElMessage.error('审核BOM失败: ' + (error as Error).message);
    console.error('Failed to approve EBOM:', error);
  }
};

// 启用BOM
const handleEnable = async (ebom: EBOM) => {
  try {
    // 假设当前用户ID为1，实际应从登录信息中获取
    const enabledBy = 1;
    await enableEBOM(ebom.id, enabledBy);
    ElMessage.success('启用BOM成功');
    loadEBOMList();
  } catch (error) {
    ElMessage.error('启用BOM失败: ' + (error as Error).message);
    console.error('Failed to enable EBOM:', error);
  }
};

// 禁用BOM
const handleDisable = async (ebom: EBOM) => {
  try {
    // 假设当前用户ID为1，实际应从登录信息中获取
    const disabledBy = 1;
    await disableEBOM(ebom.id, disabledBy);
    ElMessage.success('禁用BOM成功');
    loadEBOMList();
  } catch (error) {
    ElMessage.error('禁用BOM失败: ' + (error as Error).message);
    console.error('Failed to disable EBOM:', error);
  }
};

// 新建版本
const handleNewVersion = (ebom: EBOM) => {
  Object.assign(newVersionForm, {
    currentVersion: ebom.version,
    newVersion: '',
    changeReason: '',
    bomId: ebom.id
  });
  newVersionDialogVisible.value = true;
};

// 提交新版本
const newVersionFormRef = ref(null);
const submitNewVersion = async () => {
  try {
    await (newVersionFormRef.value as any).validate();
    const { bomId, newVersion, changeReason } = newVersionForm;
    // 假设当前用户ID为1，实际应从登录信息中获取
    const createdBy = 1;
    await createNewVersion(bomId, newVersion, createdBy, changeReason);
    ElMessage.success('创建新版本成功');
    newVersionDialogVisible.value = false;
    loadEBOMList();
  } catch (error) {
    if ((error as any).name === 'ValidationError') {
      return;
    }
    ElMessage.error('创建新版本失败');
    console.error('Failed to create new version:', error);
  }
};

// 删除BOM
const handleDelete = (ebom: EBOM) => {
  Object.assign(currentEBOM, ebom);
  deleteDialogVisible.value = true;
};

// 确认删除
const confirmDelete = async () => {
  try {
    if (currentEBOM.id) {
      await deleteEBOM(currentEBOM.id);
      ElMessage.success('删除BOM成功');
      deleteDialogVisible.value = false;
      loadEBOMList();
    }
  } catch (error) {
    ElMessage.error('删除BOM失败: ' + (error as Error).message);
    console.error('Failed to delete EBOM:', error);
  }
};

// 初始加载
onMounted(() => {
  loadEBOMList();
});
</script>

<style scoped>
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.card-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 16px;
}

.tree-node-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 5px 0;
}

.tree-node-actions {
  display: flex;
  align-items: center;
}

.el-tree-node__content {
  height: auto !important;
  padding: 5px 0;
}
</style>